// pages/me/me.js
const defaultAvatarUrl = 'https://img.yzcdn.cn/vant/cat.jpeg';
const util = require("../../utils/request");
import Toast from '@vant/weapp/toast/toast';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    avatarUrl: defaultAvatarUrl, // 头像
    nickName: "微信用户", // 昵称
    order: [], // 客户下过的订单
    dishes: [], // 菜品信息
    show: false, // 显示抽屉
    price: 0, // 选中订单的总价格
    isMember: false, // 是否为会员
    member: {}, // 会员信息
    showRegisterDialog: false, // 显示注册会员弹框
    showLookDialog: false, // 显示查看会员弹窗
    orderId: 0 // 当前展开的订单id，用于向评价页面传参
  },

  //点击头像
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail 
    this.setData({
      avatarUrl,
    })
  },

  /**
   * 查询自己的订单（已下单或已结账）
   */
  getOrderByWxId() {
      const openid = wx.getStorageSync('openid');//获取微信小程序的缓存
      util.request("/rms/order/selectOrderByWxId/" + openid, 'GET', {}, res => {
         let code = res.data.code;//请求状态码，http请求
         if(code == 200) {//如果请求成功，获取数据
             let order = res.data.data;
             if(order.length > 0) {
                 this.setData({//有数据就渲染到前端
                     order: order
                 });
             }
         }
      });
  },

  /**
   * 根据订单查询下单信息
   */
  async getDishesByOrderId(orderId) {
    if(!orderId) return;
    await util.request('/rms/dishesOrder/selectDishesByOrderId/' + orderId, 'GET', {}, res => {
        let dishes = res.data.data;
        if(dishes.length > 0) {
            for(let index in dishes) {
                dishes[index].pictureUrl = 'http://localhost:8091/profile/upload' + dishes[index].pictureUrl;
            }
            this.setData({
                dishes: dishes
            });
        }
    });
  },

  /**
   * 展开订单
   */
  onChange(event) {
    let orderId = event.detail[0];
    let order = this.data.order;
    for(let index in order) {
        if (orderId == order[index].orderId) {
            this.setData({price: order[index].actualPrize});
            break;
        }
    }
    this.getDishesByOrderId(orderId);
    this.setData({
        show: true,
        orderId: orderId
    });
  },


  /**
   * 关闭抽屉
   */
  onClose() {
      this.setData({
          show: false,
          dishes: [],
          orderId: 0
      });
  },


  /**
   * 查询会员信息
   */
  getMemberByWxId() {
    const openid = wx.getStorageSync('openid');
    util.request("/rms/member/getInfoByWxId/" + openid, 'GET', {}, res => {
        let code = res.data.code;
        if(code == 200) {
            let member = res.data.data;
            if(member == null) {
                this.setData({isMember: false});
            } else {
                this.setData({
                    isMember: true,
                    member: member
                });
            }
        }
    });
  },

  /**
   * 注册会员按钮
   */
  registerMember() {
    this.setData({showRegisterDialog: true});
  },

  /**
   * 提交注册
   */
  submitRegister() {
    let member = this.data.member;
    if(member.memberName == null || member.phone == null) {
        Toast('未填写必填信息，提交失败');
        this.cancelRegister();
        return;
    }
    member.wxId = wx.getStorageSync('openid');
    util.request("/rms/member", 'POST', member, res => {
        let code = res.data.code;
        if(code == 200) {
            Toast('注册成功');
            this.getMemberByWxId(); // 重新查询会员信息
        } else {
            Toast('注册失败');
        }
    });
  },

  /**
   * 捕获会员名称输入值
   */
  onMemberName(event) {
    this.setData({
        'member.memberName': event.detail
    });
  },

  /**
   * 捕获手机号输入值
   */
  onPhoneName(event) {
    this.setData({
        'member.phone': event.detail
    });
  },

  /**
   * 取消注册
   */
  cancelRegister() {
      this.setData({
          showRegisterDialog: false,
          member: []
      });
  },

  /**
   * 弹出查看会员弹框
   */
  lookMember() {
      this.setData({showLookDialog: true});
  },

  /**
   * 关闭查看会员弹框
   */
  cancelLookMember() {
      this.setData({showLookDialog: false});
  },

  /**
   * 充值操作
   */
  recharge() {
      let price = this.data.price;
      if(price <= 0) return;
      let memberId = this.data.member.memberId;
      util.request('/rms/member/recharge/' + memberId + '/' + price, 'PUT', {}, res => {
        let code = res.data.code;
        if(code == 200) {
            Toast('充值成功');
            this.getMemberByWxId();
        } else {
            Toast('充值失败');
        }
        this.setData({price: 0});
      });
  },

  /**
   * 点击评价按钮
   */
  onClickAssessButton() {
      wx.navigateTo({
        url: '../assess/assess?orderId=' + this.data.orderId
      });
      this.onClose();
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getOrderByWxId();
    this.getMemberByWxId();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})